package com.hainingtong.core.shiro.realm;

import com.hainingtong.core.constant.Constants;
import com.hainingtong.core.shiro.token.BaseToken;
import com.hainingtong.core.shiro.token.LoginType;
import com.hainingtong.core.shiro.token.PhoneCodeToken;
import com.hainingtong.core.util.RedisUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.util.StringUtils;

public class PhoneCodeRealm extends AuthorizingRealm {
    @Override
    public boolean supports(AuthenticationToken token) {
        //  return ((BaseToken)token).getLoginType().equals(LoginType.PhoneCode); // 这样也可以，和下一句作用一样
        return token instanceof PhoneCodeToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (!StringUtils.hasText(authenticationToken.getPrincipal().toString())) {
            return null;
        }

        PhoneCodeToken token = (PhoneCodeToken) authenticationToken;

        // 从redis获取之前生成的数据库
        String code = (String) RedisUtil.get(Constants.REDIS_PHONE_CODE_PREFIX + token.getPrincipal());
        if (code == null) {
            return null;
        }

        return new SimpleAuthenticationInfo(token.getPrincipal(), code, getName());
    }
}
